package com.wnhz.work.yz.activity;

import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.umeng.socialize.shareboard.SnsPlatform;
import com.umeng.socialize.utils.ShareBoardlistener;
import com.wnhz.work.yz.BaseActivity;
import com.wnhz.work.yz.MyApplication;
import com.wnhz.work.yz.R;
import com.wnhz.work.yz.adapter.HomeFragmentAdapter;
import com.wnhz.work.yz.base.BaseFragment;
import com.wnhz.work.yz.bean.BathroomDetailBean;
import com.wnhz.work.yz.bean.ClassifyDetilsBean;
import com.wnhz.work.yz.bean.Finish1;
import com.wnhz.work.yz.bean.Fragment1Bean;
import com.wnhz.work.yz.bean.SkyIdBean;
import com.wnhz.work.yz.fragment.shoppingdetails.Fragment1;
import com.wnhz.work.yz.fragment.shoppingdetails.Fragment2;
import com.wnhz.work.yz.fragment.shoppingdetails.Fragment3;
import com.wnhz.work.yz.fragment.shoppingdetails.Fragment4;
import com.wnhz.work.yz.utils.Url;
import com.wnhz.work.yz.utils.xutils3.MyCallBack;
import com.wnhz.work.yz.utils.xutils3.XUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static com.wnhz.work.yz.utils.Tag.MULTIPLESELECT;

/**
 * ---商品详情
 */
public class ShoppingDetailsActivity extends BaseActivity implements View.OnClickListener {

    private List<BaseFragment>
            list_fragment = new ArrayList<>(); //定义要装fragment的列表
    private List<String> list_title = new ArrayList<>(); //tab名称列表
    private TabLayout tabLayout;
    private HomeFragmentAdapter homeFragmentAdapter;
    private ViewPager viewPager;

    private Fragment1 fragment1;
    private Fragment2 fragment2;
    private Fragment3 fragment3;
    private Fragment4 fragment4;

    public String goodsId;
    public String goodsPrice;
    private String getOrderState;
    private Fragment1Bean bean;
    private ArrayList<Fragment1Bean> beanList = new ArrayList<>();
    private ArrayList<ClassifyDetilsBean> skuList = new ArrayList<>();
    private ArrayList<SkyIdBean> skusList = new ArrayList<>();
    private ImageView iv_collect;
    private TextView tv_collect;
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(Finish1 event) {
        finish();
    }


    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);//反注册EventBus
        super.onDestroy();
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shopping_details);
        EventBus.getDefault().register(this);
        iv_collect = (ImageView) findViewById(R.id.iv_collect);
        tv_collect = (TextView) findViewById(R.id.tv_collect);
        findViewById(R.id.rl_fen).setOnClickListener(this);
        initTitle();
        qqShare();
        initData();

        tabLayout = (TabLayout) findViewById(R.id.tabLayout);
        viewPager = (ViewPager) findViewById(R.id.viewpager);
        list_title.clear();
        list_title.add("详情");
        list_title.add("参数");
        list_title.add("视频");
        list_title.add("安装说明");
        list_fragment.clear();
        fragment1 = new Fragment1();
        fragment2 = new Fragment2();
        fragment3 = new Fragment3();
        fragment4 = new Fragment4();
        list_fragment.add(fragment1);
        list_fragment.add(fragment2);
        list_fragment.add(fragment3);
        list_fragment.add(fragment4);
        homeFragmentAdapter = new HomeFragmentAdapter(getSupportFragmentManager(), list_fragment, list_title);
        viewPager.setAdapter(homeFragmentAdapter);
        tabLayout.setupWithViewPager(viewPager);

        viewPager.setOffscreenPageLimit(list_fragment.size());//一次加载多少个
        upload();

    }

    private void initClick() {
        findViewById(R.id.tv_inCart).setOnClickListener(this);
        findViewById(R.id.rl_collect).setOnClickListener(this);
        findViewById(R.id.rl_service).setOnClickListener(this);

    }

    private static final String TAG = "ShoppingDetailsActivity";
    private String bannerUrl;

    private void upload() {
        showDialog();
        Map<String, Object> map = new HashMap<>();
        String token="";
        if(MyApplication.getInstance().getUserBean()!=null && MyApplication.getInstance().getUserBean().getToken()!=null && !MyApplication.getInstance().getUserBean().getToken().equals("")){
            token=MyApplication.getInstance().getUserBean().getToken();
        }
        map.put("token", token);

      //  Log.e(TAG, "================token: == " +  MyApplication.getInstance().getUserBean().getToken());

        map.put("goodsId", goodsId);
        MyApplication.getInstance().jiji = goodsId;
        XUtil.Post(Url.GOODS_GETGOODSDETAIL, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                closeDialog();
                super.onSuccess(result);
                Log.i(TAG, "onSuccess: upload: == " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    if ("1".equals(res)) {
                        bean = new Fragment1Bean();
                        Gson gson = new Gson();
                        JSONObject jsonObject1 = jsonObject.optJSONObject("info");
                        String collect_status = jsonObject1.optString("collect_status");
                        // Log.i("onSuccess: upload: ==","--"+collect_status);
                        JSONArray banner = jsonObject1.optJSONArray("banner");
                        if (banner.length() > 0) {
                            bannerUrl = banner.optString(0);
                        }
                        // Log.e("---",banner.toString()+"----"+banner.optString(0));
                        if ("0".equals(collect_status)) {
                        } else {
                            iv_collect.setImageResource(R.mipmap.ic_shangpinshoucang_li);
                            tv_collect.setText("已收藏");
                        }
                        bean = gson.fromJson(jsonObject.optString("info"), Fragment1Bean.class);
                        System.out.println("jsonObject.optString======"+jsonObject.optString("info"));
                        beanList.add(bean);
                        fragment1.setData(bean);
                        fragment2.settext(bean);
                        skuList.clear();
                        skuList.addAll(bean.getSku());


                        JSONObject jsonObject2 = jsonObject1.optJSONObject("sku_attr");

                        Iterator iterator = jsonObject2.keys();                       // jsonObject2是JSONObject对象
                        while (iterator.hasNext()) {
                            String key = iterator.next() + "";
                            String v = jsonObject2.optString(key);
                            SkyIdBean skuBean = new SkyIdBean();
                            skuBean = gson.fromJson(v, SkyIdBean.class);
                            skuBean.setKey(key);
                            Log.i(TAG, "onSuccess:key= " + key);
                            skusList.add(skuBean);
                        }

                        bean.setSkuattr(skusList);


                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                closeDialog();
                initClick();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                closeDialog();
                super.onError(ex, isOnCallback);
            }
        });
    }

    private void initData() {
        goodsId = getIntent().getStringExtra("goodsId");
    }

    private TextView title;

    private void initTitle() {
        findViewById(R.id.btn_main_left).setOnClickListener(this);
        findViewById(R.id.btn_main_right).setOnClickListener(this);
        findViewById(R.id.btn_main_right).setVisibility(View.VISIBLE);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_main_left:
                finish();
                break;

            case R.id.btn_main_right:

                EventBus.getDefault().post(new Finish1());
                EventBus.getDefault().post(new BathroomDetailBean());
                finish();
                break;

            //加入购物车
            case R.id.tv_inCart:
              //  if(bean.getSku()!=null) {
                    ActivityCompat.startActivityForResult(this,
                            new Intent(this, MultipleSelectActivity.class)
                                    //.putExtra("price", goodsPrice)
                                    .putExtra("goodsId", goodsId)
                                    .putExtra("sku", skuList).putExtra("bean", bean)
                                    .putExtra("from", "shopping")
                                    .putExtra("imgUrl", bannerUrl)
                                    .putExtra("beanList", beanList), MULTIPLESELECT, null);

//                }else {
//
//                }
                break;
            case R.id.rl_service:

                if (MyApplication.getInstance().getUserBean() == null) {
                    MyToast("请登录!");
                    Intent intent2 = new Intent(this, LoginNewActivity.class);
                    startActivity(intent2);
                    return;
                }
                Intent intent = new Intent(this, YZServiceSelectActivity.class);
                startActivity(intent);
                break;
            case R.id.rl_collect:
                if ("已收藏".equals(tv_collect.getText())) {
                    cancleCollect();
                } else
                    collect();
                break;
            case R.id.rl_fen:
                mShareAction.open();
                break;
        }
    }

    private void cancleCollect() {
        Map<String, Object> map = new HashMap<>();
        try {
            map.put("token", MyApplication.getInstance().getUserBean().getToken());
        } catch (Exception e) {
            startActivity(new Intent(getApplicationContext(), LoginFirstActivity.class));
            return;
        }
        map.put("goodsId", goodsId);
        map.put("type", "1");
        //   Log.i(TAG, "upload: == " + goodsId);
        XUtil.Post(Url.GOODS_CANCLECOLLECTGOODS, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                closeDialog();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    if ("1".equals(res)) {
                        iv_collect.setImageResource(R.mipmap.ic_shangpinshoucang_nor);
                        tv_collect.setText("收藏");
                    }
                    toast = jsonObject.optString("info");

                } catch (JSONException e) {
                    e.printStackTrace();
                }

                super.onSuccess(result);

            }

            @Override
            public void onFinished() {
                closeDialog();
                MyToast(toast);
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                closeDialog();
                Log.i("---", "onError=" + ex);

                super.onError(ex, isOnCallback);
            }
        });
    }

    private String toast;

    private void collect() {
        Map<String, Object> map = new HashMap<>();
        try {
            map.put("token", MyApplication.getInstance().getUserBean().getToken());
        } catch (Exception e) {
            startActivity(new Intent(getApplicationContext(), LoginFirstActivity.class));
            return;
        }
        map.put("goodsId", goodsId);
        map.put("type", "1");
        //   Log.i(TAG, "upload: == " + goodsId);
        XUtil.Post(Url.GOODS_COLLECTGOODS, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                closeDialog();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    if ("1".equals(res)) {
                        iv_collect.setImageResource(R.mipmap.ic_shangpinshoucang_li);
                        tv_collect.setText("已收藏");
                    }

                    toast = jsonObject.optString("info");

                } catch (JSONException e) {
                    e.printStackTrace();
                }

                super.onSuccess(result);

            }

            @Override
            public void onFinished() {
                closeDialog();
                MyToast(toast);
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                closeDialog();
                Log.i("---", "onError=" + ex);

                super.onError(ex, isOnCallback);
            }
        });
    }

    private ShareAction mShareAction;
    private UMShareListener mShareListener;

    private void qqShare() {
        mShareListener = new CustomShareListener(ShoppingDetailsActivity.this);
        /*增加自定义按钮的分享面板*/
        mShareAction = new ShareAction(ShoppingDetailsActivity.this).setDisplayList(//SHARE_MEDIA.WEIXIN_FAVORITE微信收藏
                SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE,
                SHARE_MEDIA.QQ, SHARE_MEDIA.QZONE)

                .setShareboardclickCallback(new ShareBoardlistener() {
                    @Override
                    public void onclick(SnsPlatform snsPlatform, SHARE_MEDIA share_media) {
                        if (snsPlatform.mShowWord.equals("umeng_sharebutton_copy")) {
                            Toast.makeText(ShoppingDetailsActivity.this, "复制文本按钮", Toast.LENGTH_LONG).show();
                        } else if (snsPlatform.mShowWord.equals("umeng_sharebutton_copyurl")) {
                            Toast.makeText(ShoppingDetailsActivity.this, "复制链接按钮", Toast.LENGTH_LONG).show();

                        } else {

                            if (bean == null) {
                                return;
                            }
                            MyApplication.getInstance().jiji = bean.getGoods_id();
                            UMWeb web = new UMWeb(bean.getShare_url());
                            web.setTitle(bean.getShare_title());
                            web.setDescription(bean.getShare_des());
                            web.setThumb(new UMImage(ShoppingDetailsActivity.this, bean.getShare_img()));


                            new ShareAction(ShoppingDetailsActivity.this).withMedia(web)
                                    .setPlatform(share_media)
                                    .setCallback(mShareListener)
                                    .share();
                        }
                    }
                });
    }

    private static class CustomShareListener implements UMShareListener {

        private WeakReference<BaseActivity> mActivity;

        private CustomShareListener(ShoppingDetailsActivity activity) {
            mActivity = new WeakReference(activity);
        }

        @Override
        public void onStart(SHARE_MEDIA platform) {

        }

        @Override
        public void onResult(SHARE_MEDIA platform) {

            if (platform.name().equals("WEIXIN_FAVORITE")) {
                Toast.makeText(mActivity.get(), platform + " 收藏成功啦", Toast.LENGTH_SHORT).show();
            } else {
                if (platform != SHARE_MEDIA.MORE && platform != SHARE_MEDIA.SMS
                        && platform != SHARE_MEDIA.EMAIL
                        && platform != SHARE_MEDIA.FLICKR
                        && platform != SHARE_MEDIA.FOURSQUARE
                        && platform != SHARE_MEDIA.TUMBLR
                        && platform != SHARE_MEDIA.POCKET
                        && platform != SHARE_MEDIA.PINTEREST
                        && platform != SHARE_MEDIA.INSTAGRAM
                        && platform != SHARE_MEDIA.GOOGLEPLUS
                        && platform != SHARE_MEDIA.YNOTE
                        && platform != SHARE_MEDIA.EVERNOTE) {
                    Log.e("----", "ffff");
                    upfen();
                    Toast.makeText(mActivity.get(), platform + " 分享成功啦", Toast.LENGTH_SHORT).show();
                }

            }
        }

        private void upfen() {
            Map<String, Object> map = new HashMap<>();
            map.put("type", 0);
            map.put("packageid", MyApplication.getInstance().jiji);
            Set keys = map.keySet();
            if (keys != null) {
                Iterator iterator = keys.iterator();
                while (iterator.hasNext()) {
                    Object key = iterator.next();
                    Object value = map.get(key);
                    Log.e("----" + key, "" + value + "\n");
                }
            }
            XUtil.Post(Url.API_SHARERETURN, map, new MyCallBack<String>() {
                @Override
                public void onSuccess(String result) {
                    super.onSuccess(result);
                    Log.i("----", "onSuccess:= " + result);

                }

                @Override
                public void onFinished() {
                    super.onFinished();
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    super.onError(ex, isOnCallback);
                    ex.printStackTrace();
                }
            });


        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            if (platform != SHARE_MEDIA.MORE && platform != SHARE_MEDIA.SMS
                    && platform != SHARE_MEDIA.EMAIL
                    && platform != SHARE_MEDIA.FLICKR
                    && platform != SHARE_MEDIA.FOURSQUARE
                    && platform != SHARE_MEDIA.TUMBLR
                    && platform != SHARE_MEDIA.POCKET
                    && platform != SHARE_MEDIA.PINTEREST
                    && platform != SHARE_MEDIA.INSTAGRAM
                    && platform != SHARE_MEDIA.GOOGLEPLUS
                    && platform != SHARE_MEDIA.YNOTE
                    && platform != SHARE_MEDIA.EVERNOTE) {
                Toast.makeText(mActivity.get(), platform + " 分享失败啦", Toast.LENGTH_SHORT).show();
                if (t != null) {
                    com.umeng.socialize.utils.Log.d("throw", "throw:" + t.getMessage());
                }
            }

        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {

            Toast.makeText(mActivity.get(), platform + " 分享取消了", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /** attention to this below ,must add this**/
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 屏幕横竖屏切换时避免出现window leak的问题
     */
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mShareAction.close();
    }

}
